/* eslint-disable no-underscore-dangle */
const client = require('../models/redisdb');

const prefix = 'channel_demo_ess';

class DbService {
  async set(key, value) {
    const valueStr = typeof value === 'object' ? JSON.stringify(value) : value;
    const result = await client.set(`${prefix}:${key}`, valueStr, {
      EX: 2592000,
    });
    return result;
  }

  async get(key) {
    const result = await client.get(`${prefix}:${key}`);

    try {
      return JSON.parse(result);
    } catch (err) {
      console.log('db get jsonparse error', err);
    }
    return {};
  }

  async del(key) {
    const result = await client.del(`${prefix}:${key}`);
    return result;
  }

  async hSet(key, field, value) {
    let valueStr = value;
    if (typeof value === 'object') {
      valueStr = JSON.stringify({
        ...value,
        id: field,
      });
    }
    const result = client.hSet(`${prefix}:${key}`, field, valueStr || '');
    return result;
  }

  async hGet(key, field) {
    const result = await client.hGet(`${prefix}:${key}`, field);
    try {
      return JSON.parse(result);
    } catch (err) {
      console.log('db hGet jsonparse error', err);
    }
    return {};
  }

  async hGetAll(key) {
    const allResults = await client.hGetAll(`${prefix}:${key}`);
    if (allResults) {
      const formatedResults = {};
      Object.entries(allResults).forEach((key, val) => {
        try {
          formatedResults[key] = JSON.parse(val);
        } catch (err) {
          console.log('db hGetAll jsonparse error', err);
        }
      });
      return formatedResults;
    }
    return {};
  }

  async hDel(key, field) {
    return await client.hDel(`${prefix}:${key}`, field);
  }

  async hVals(key) {
    const allResults = await client.hVals(`${prefix}:${key}`);

    if (allResults) {
      return allResults.map((r) => {
        if (r) {
          try {
            return JSON.parse(r);
          } catch (err) {
            console.log('db hVals jsonparse error', err);
            console.log('db hVals jsonparse error json', r);
          }
        }
        return {};
      });
    }
    return [];
  }

  async lPush(key, data, options) {
    const str = JSON.stringify(data);
    return await client.lPush(`${prefix}:${key}`, str, options);
  }

  async lRange(key, start = 0, end = -1) {
    const result = await client.lRange(`${prefix}:${key}`, start, end);
    return result.filter(item => item).map((r) => {
      if (r) {
        try {
          return JSON.parse(r);
        } catch (err) {
          console.log('db lRange jsonparse error', err);
          console.log('db hVals jsonparse error json', r);
        }
      }
      return {};
    });
  }
}

module.exports = DbService;
